package cn.btks.commonserver.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author zhangjing
 * 2020/3/26 14:52
 * 获取token信息
 */
public class JwtUtil {

    public static final String jwtsSecret = "btkssxyd";

    /**
     * 获取token中的参数值
     *
     * @param request
     * @param secret 用于进行签名的秘钥
     * @return
     * @throws Exception
     */
    public static Map<String, Object> getTokenInfo(HttpServletRequest request, String secret) throws Exception {
        //从 http 请求头中取出 token
        String token = request.getHeader("token");

        Optional<Claims> claims = getClaimsFromToken(token, secret);
        if (claims.isPresent()) {
            Map<String, Object> info = new HashMap<String, Object>();
            Set<String> keySet = claims.get().keySet();
            //通过迭代，提取token中的参数信息
            Iterator<String> iterator = keySet.iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                Object value = claims.get().get(key);
                info.put(key, value);

            }
            return info;
        }
        return null;
    }

    /**
     * 利用jwt解析token信息.
     *
     * @param token  要解析的token信息
     * @param secret 用于进行签名的秘钥
     * @return
     * @throws Exception
     */
    public static Optional<Claims> getClaimsFromToken(String token, String secret) throws Exception {
        Claims claims;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
            return Optional.of(claims);
        } catch (Exception e) {
            System.out.println(e);
            return Optional.empty();
        }
    }
}
